package org.monkey.socket.plugin.handler;

import cn.hutool.json.JSONUtil;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.monkey.socket.plugin.entity.SocketMsg;
import org.monkey.socket.plugin.service.IMsgAcceptHandler;
import org.monkey.socket.plugin.service.IMsgChannelManage;

/**
 * 引言
 * 其实在消息发送前
 * 可以先将消息存入redis A用户的消息队列,
 * 如果消息channel writeFlush成功 则删除该消息。
 * 如果消息一定时间累计未被消费 则将消息入库并标识该用户数据库存在未消费数据
 * 用户上线时 如果不存在数据库未读标识 则从redis集群拉取离线消息
 * 否则 从数据库拉取离线消息
 */
@Data
@Slf4j
public class DefaultMsgAcceptHandler implements IMsgAcceptHandler {
  private IMsgChannelManage channelManage;

  public DefaultMsgAcceptHandler(IMsgChannelManage channelManage) {
    this.channelManage = channelManage;
  }

  @Override
  public boolean acceptHandle(SocketMsg socketMsg) {
    String namespace = socketMsg.getNamespace();
    String userId = socketMsg.getTo();
    ChannelGroup channelGroup = channelManage.getChannelGroupByArgs(namespace, userId);
    if (channelGroup != null) {
      log.info("send msg 2 user's client:namespace:{},userId={},msg={}", namespace, userId,
          socketMsg);
      channelGroup.writeAndFlush(new TextWebSocketFrame(JSONUtil.toJsonStr(socketMsg)));
    }
    // stop handler
    return false;
  }
}
